/*
 * Copyright(C) 2019 FUYUN DATA SERVICES CO.,LTD. - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * 该源代码版权归属福韵数据服务有限公司所有
 * 未经授权，任何人不得复制、泄露、转载、使用，否则将视为侵权
 *
 */

import * as React from "react";
import { connect } from "react-redux";
import { IRootState, Dispatch } from "../../../../store";
import { Form, Button, Table, Modal, Tree, Input } from "antd";

import { FormComponentProps } from "antd/lib/form";
import TitleCard from "src/components/TitleCard";
import menuData from "src/common/menu";
import moment from "moment";

const mapStateToProps = ({ user, loading }: IRootState) => ({
  user,
  loading: loading.effects.user.getUserList as any
});
const mapDispatchToProps = ({ user }: Dispatch) => ({
  getUserList: (payload: any) => user.getUserList(payload),
  getUserById: (id: any) => user.getUserById(id),
  saveRole: (payload: any) => user.saveRole(payload),
  bindRole: (payload: any) => user.bindRole(payload),
  deleteRole: (userId: string) => user.deleteRole(userId)
});

type connectedProps = ReturnType<typeof mapStateToProps> &
  ReturnType<typeof mapDispatchToProps>;

interface IState {
  visible: boolean;
  edit: boolean;
  treeData: any[];
  searchValue: any;
  currPage: number;
  selectTree: any;
  selectUserId: string;
  selectKeys: any[];
}

interface IProps extends connectedProps {
  loading: boolean;
}

const { TreeNode } = Tree;
let selectData: any = [];
class RoleUserList extends React.Component<
  IProps & FormComponentProps,
  IState
> {
  public state = {
    visible: false,
    edit: false,
    treeData: [],
    searchValue: "",
    currPage: 0,
    selectTree: [],
    selectUserId: "",
    selectKeys: []
  };

  public componentDidMount = () => {
    const { getUserList } = this.props;
    getUserList({
      size: 10,
      name: ""
    });
  };

  public editHandle = (id: any) => {
    console.log("editHandle");
  };

  public statusHandle = (id: any) => {
    console.log("statusHandle");
  };

  public handleOk = async () => {
    const { saveRole, deleteRole } = this.props;
    await deleteRole(this.state.selectUserId);
    saveRole(selectData);
    selectData = [];
    this.setState({
      visible: false,
      selectUserId: ""
    });
  };

  public handleCancel = () => {
    selectData = [];
    this.setState({
      visible: false,
      selectUserId: ""
    });
  };

  public showModal = async (id: any) => {
    const { getUserById, bindRole } = this.props;
    await getUserById(id);
    await bindRole(id);
    this.loadTreeData();
    this.setState({
      visible: true,
      edit: false,
      selectUserId: id
    });
  };

  public loadTreeData = () => {
    const tempData: any = [];
    const { roleList } = this.props.user;
    const tempArr: any = [];
    menuData.map((v: any, index: any) => {
      const temp: any = {
        key: String(index),
        title: v.name,
        value: v.path,
        children: []
      };
      let tempNumber = roleList.findIndex(role => role.path === v.path);
      if (tempNumber !== -1) {
        tempArr.push(String(index));
      }
      v.children.map((childItem: any, childIndex: any) => {
        const childrenTemp = {
          key: String(index) + childIndex,
          title: childItem.name,
          value: childItem.path
        };
        tempNumber = roleList.findIndex(role => role.path === childItem.path);
        if (tempNumber !== -1) {
          tempArr.push(String(index) + childIndex);
        }
        temp.children.push(childrenTemp);
      });
      tempData.push(temp);
    });

    this.setState({
      treeData: tempData,
      selectKeys: tempArr
    });
    this.onloadTree(roleList);
  };

  public inputChange = (e: any) => {
    this.setState({
      searchValue: e.target.value
    });
  };

  public changePage(pageNumber: any, pageSize: any, props: any) {
    const { getUserList } = this.props;
    const payload = {
      name: this.state.searchValue,
      page: pageNumber - 1,
      size: pageSize
    };
    this.setState({
      currPage: pageNumber
    });

    getUserList(payload);
  }

  public searchHandle = () => {
    const { getUserList } = this.props;
    getUserList({
      size: 10,
      name: this.state.searchValue
    });
  };

  public checkedTree = (value: any, nodes: any) => {
    selectData = [];
    // console.log(nodes,this.state.treeData)
    const { treeData } = this.state;
    nodes.halfCheckedKeys.map((v: any) => {
      const parentObj: any =
        treeData[treeData.findIndex((item: any) => item.key === v)];
      const tempObj = {
        userId: this.state.selectUserId,
        path: parentObj.value
      };
      selectData.push(tempObj);
    });

    nodes.checkedNodesPositions.map((item: any) => {
      const tempItem = item.node.props.dataRef;
      const tempObj = { userId: this.state.selectUserId, path: tempItem.value };
      selectData.push(tempObj);
    });
  };

  public onloadTree = (roleList: any) => {
    roleList.map((item: any, index: any) => {
      if (index === 0) {
        this.setState({
          selectUserId: item.userId
        });
      }
      const tempObj = { userId: item.userId, path: item.path };
      selectData.push(tempObj);
    });
  };

  public tableRender() {
    const { userList } = this.props.user;
    const column = [
      {
        title: "序号",
        dataIndex: "seq",
        render: (text: any, record: any, index: any) => {
          return index + 1;
        }
      },
      {
        title: "用户名",
        dataIndex: "account"
      },
      {
        title: "名称",
        dataIndex: "name"
      },
      {
        title: "状态",
        dataIndex: "status",
        render: (text: any, record: any, index: any) => {
          if (text === "0") {
            return "启用";
          } else {
            return "停用";
          }
        }
      },
      {
        title: "创建时间",
        dataIndex: "createTime",
        render: (text: any, record: any, index: any) => {
          return (
            <span>
              {text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : " - -"}
            </span>
          );
        }
      },
      {
        title: "上次登录时间",
        dataIndex: "modifyTime",
        render: (text: any, record: any, index: any) => {
          return (
            <span>
              {text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : " - -"}
            </span>
          );
        }
      },
      {
        title: "操作",
        dataIndex: "",
        render: (text: any, record: any, index: any) => {
          return (
            <div>
              <Button
                type="primary"
                size="small"
                style={{ marginRight: "10px" }}
                onClick={() => this.showModal(record.id)}
              >
                权限分配
              </Button>
            </div>
          );
        }
      }
    ];

    return <Table dataSource={userList} columns={column} rowKey={"id"} />;
  }

  public renderTreeNodes = (tData: any) =>
    tData.map((item: any) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode title={item.title} key={item.key} dataRef={item}>
          {item.title}
        </TreeNode>
      );
    });

  public render() {
    const { roleList } = this.props.user;
    console.log(roleList);
    return (
      <div className="message-container" style={{ paddingTop: 32 }}>
        <div style={{ marginLeft: "20px" }}>
          <b>名称:</b>
          <Input
            style={{ width: "200px", marginLeft: "10px" }}
            onChange={(e: any) => this.inputChange(e)}
          />
          <Button
            type="primary"
            style={{ marginLeft: "10px" }}
            onClick={this.searchHandle}
          >
            查询
          </Button>
        </div>
        <TitleCard style={{ paddingTop: 32 }}>{this.tableRender()}</TitleCard>

        <Modal
          title={"权限分配"}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText="保存"
          cancelText="取消"
          destroyOnClose={true}
          visible={this.state.visible}
        >
          <Tree
            checkable={true}
            onCheck={this.checkedTree}
            defaultSelectedKeys={this.state.selectKeys}
            defaultCheckedKeys={this.state.selectKeys}
          >
            {this.renderTreeNodes(this.state.treeData)}
          </Tree>
        </Modal>
      </div>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Form.create<IProps & FormComponentProps>({})(RoleUserList));
